package cn.tohsaka.factory.dockercraft.Engines

import org.apache.velocity.VelocityContext
import org.apache.velocity.app.VelocityEngine
import java.io.File
import java.io.PrintWriter
import java.io.StringWriter
import java.nio.charset.Charset
import java.util.*
/**
 * Created by Xmsoft on 2016/7/15.
 */
class veEngine(var basePath:String){
    var engine= VelocityEngine();
    init {
        engine.setProperty("input.encoding","UTF-8");
        engine.setProperty("output.encoding","UTF-8");
        engine.init()
    }
    fun execute(path:String,ctx: VelocityContext = VelocityContext()):String{
        return execute(File(basePath+ File.separator+path),ctx);
    }
    fun execute(file: File, ctx: VelocityContext = VelocityContext()):String{
        try {
            val sw = StringWriter();
            engine.evaluate(ctx,sw,"",file.bufferedReader());
            return sw.toString();
        }catch (e:Exception){
            return exception(e);
        }
    }
    fun exception(e:Exception):String{
        val sw= StringWriter();
        sw.append("<!DOCTYPE html><html lang=\"zh-CN\"><head><meta charset=\"utf-8\"></head><body><h3>Uncaught exception</h3><hr><pre>");
        e.printStackTrace(PrintWriter(sw));
        sw.append("</pre></body></html>");
        return sw.toString();
    }
}